#!/usr/bin/env python3

#            ---------------------------------------------------
#                              Omega Framework                                
#            ---------------------------------------------------
#                  Copyright (C) <2020>  <Entynetproject>       
#
#        This program is free software: you can redistribute it and/or modify
#        it under the terms of the GNU General Public License as published by
#        the Free Software Foundation, either version 3 of the License, or
#        any later version.
#
#        This program is distributed in the hope that it will be useful,
#        but WITHOUT ANY WARRANTY; without even the implied warranty of
#        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#        GNU General Public License for more details.
#
#        You should have received a copy of the GNU General Public License
#        along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os

os.system("printf '\033]2;Omega Framework\a'")

VERSION = "3.0"

import src  # spread Omega sources
import random
import argparse
import subprocess as sp
import sys

import core
import ui.input
import ui.output
import ui.interface
from ui.color import colorize
from datatypes import Path

def parser_help_formatter(prog):
    """argparser help output formatter"""
    kwargs = dict()
    kwargs['width'] = ui.output.columns()
    kwargs['max_help_position'] = 34
    fmt = argparse.HelpFormatter(prog, **kwargs)
    return fmt

def run_process(cmd: list) -> str:
    """get output of given shell command"""
    child = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.DEVNULL)
    streamdata = child.communicate()[0]
    if child.returncode != 0:
        return ""
    return streamdata.decode("utf-8").strip()


def rand_message() -> str:
    """return a random funny message"""
    msg_list = Path(src.BASEDIR + "data/messages.lst").readlines()
    return random.choice(msg_list).strip()


def cmdrun(iface, cmdobj, show_err=False) -> int:
    """run an Omega command
    handle syntax errors & return command's retcode
    """
    try:
        retval = iface.interpret(cmdobj)
    except (SyntaxWarning, SyntaxError) as err:
        retval = iface.onexception(err)
    return retval


# pylint: disable=too-many-branches
def main() -> int:
    """Omega main function
    """
    # Make Omega usable as shebang for scripting

    # Enable stdout wrapper
    sys.stdout = ui.output.Wrapper(backlog=True)

    # determine if the interface would run in interactive mode
    interactive = False
    if ui.input.isatty():
        interactive = True

    # make this variable accessible from Omega core
    ui.interface.interactive = interactive

    # Start shell interface
    iface = ui.interface.Shell()
        
    if interactive and ui.output.isatty():
        logo = Path(src.BASEDIR + "data/logo.ascii").read()
        cmdrun(iface, "clear")
        print(logo)
        print("")
        print("Omega Framework v3.0")
        print("--------------------")
        print("")

    iface.init()

    retval = 0

    if interactive or not ui.input.isatty():
        iface.cmdloop()

    return retval


if __name__ == "__main__":
    sys.exit(main())
else:
    def check_import():
        """check whether this file is imported for a CI test"""
        launcher = os.path.abspath(__file__)
        test_dir = os.path.join(os.path.dirname(launcher), "test/")
        caller = os.path.abspath(sys.argv[0])
        if not caller.startswith(test_dir):
            sys.exit('[-] Omega must be run from launcher: ' + launcher)
    check_import()
